<template>
  <div class="canvas-container">
    <!-- 工具栏 -->
    <Toolbar @add-node="handleAddNode" @save="handleSave" @reset="handleReset" />
   

    <!-- 主要内容区域 -->
    <div class="main-content">
       <ContextMenu :menu="[
            { label: '删dfgdfgdfg除', action: 'delete' },
            { label: '复制', action: 'copy' },
            { label: '粘贴', action: '1' },
            { label: '粘贴', action: '2' },
            { label: '粘贴', action: '3' }
          ]" @select="handleContextMenuSelect">
           <div>
            测试上下文菜单
           </div>

          </ContextMenu>
      <!-- 节点库面板 -->
      <NodeLibrary v-if="showNodeLibrary" class="node-library" @add-node="handleAddNodeFromLibrary"
        @close="showNodeLibrary = false" />

      <!-- 画布区域 -->
      <div ref="canvasContainer" class="canvas-area" @wheel="handleWheel" @mousedown="handleMouseDown"
        @mousemove="handleMouseMove" @mouseup="handleMouseUp">
        <svg ref="svg" class="canvas-svg" :style="{
          transform: `translate(${panX}px, ${panY}px) scale(${scale})`
        }">
          <!-- 网格背景 -->
          <defs>
            <pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse">
              <path d="M 20 0 L 0 0 0 20" fill="none" stroke="#e0e0e0" stroke-width="1" />
            </pattern>
          </defs>
          <rect x="-50000" y="-50000" width="100000" height="100000" fill="url(#grid)" />

          <!-- 连接线 -->
          <Connection v-for="connection in connections" :key="connection.id" :connection="connection"
            :source-node="getNodeById(connection.sourceNodeId)" :target-node="getNodeById(connection.targetNodeId)" />

          <Connection1 v-if="connectionSourceNodeId && connection && newConnectionPath"
            :source-node="getNodeById(connectionSourceNodeId)" :targetXY="newConnectionPath" :connection="connection" />
        </svg>

        <!-- 节点容器 -->
        <div class="nodes-container" :style="{
          transform: `translate(${panX}px, ${panY}px) scale(${scale})`
        }">
          <ContextMenu :menu="[
            { label: '删除', action: 'delete' },
            { label: '复制', action: 'copy' },
            { label: '粘贴', action: 'paste' }
          ]" @select="handleContextMenuSelect">
            <Node v-for="node in nodes" :key="node.id" :node="node" :scale="scale" :pan-x="panX" :pan-y="panY"
              @node-select="handleNodeSelect" @createConnection="handleCreateConnection"
              @connectionTargetNode="handleConnectionTargetNode" />
          </ContextMenu>

        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'
import Toolbar from '@/components/Toolbar.vue'
import NodeLibrary from '@/components/NodeLibrary.vue'
import Node from '@/components/Node.vue'
import Connection from '@/components/Connection.vue'
import Connection1 from '@/components/Connection1.vue'
import ContextMenu from '@/components/ContextMenu.vue'


export default {
  name: 'Canvas',
  components: {
    Toolbar,
    NodeLibrary,
    Node,
    Connection,
    Connection1,
    ContextMenu
  },
  data() {
    return {
      isDragging: false,
      lastMouseX: 0,
      lastMouseY: 0,
      showNodeLibrary: true,
      connectionSourceNodeId: null,
      connectionTargetXY: null,
      sourcePoint: null
    }
  },
  computed: {
    ...mapState(['nodes', 'connections', 'selectedNodeIds', 'scale', 'panX', 'panY', 'newConnectionPath']),

    ...mapGetters(['getNodeById']),

    connection() {
      return {
        id: new Date().getTime(),
        sourcePoint: this.sourcePoint,
        style: {
          strokeColor: this.getNodeById(this.connectionSourceNodeId)?.style.borderColor,
          strokeWidth: 2
        }
      }
    },

    connectionSourceNode() {
      return this.connectionSourceNodeId ? this.getNodeById(this.connectionSourceNodeId) : null
    }
  },
  methods: {
    ...mapActions(['updateNodePosition', 'selectNode', 'addNode', 'updateCanvasTransform', 'addNodeToStore']),

    //处理上下文菜单选择
    handleContextMenuSelect(action) {
      console.log(action, '上下文菜单选择');
    },
    //处理创建连接线
    handleCreateConnection(connectionSourceNodeId, point) {
      this.connectionSourceNodeId = connectionSourceNodeId
      this.sourcePoint = point
    },
    //处理连接目标节点
    handleConnectionTargetNode(connectionTargetXY) {
      // console.log(connectionTargetXY,'连接目标节点');// 连接目标节点
      this.connectionTargetXY = connectionTargetXY
    },

    // 处理鼠标滚轮缩放
    handleWheel(event) {
      event.preventDefault()

      // 获取画布容器的边界信息
      const canvasRect = this.$refs.canvasContainer.getBoundingClientRect()

      // 计算鼠标相对于画布容器的位置
      const mouseX = event.clientX - canvasRect.left
      const mouseY = event.clientY - canvasRect.top

      // 计算缩放因子
      const delta = event.deltaY > 0 ? 0.9 : 1.1
      const newScale = Math.max(0.1, Math.min(3, this.scale * delta))

      // 计算缩放前鼠标在画布坐标系中的位置
      const mouseCanvasX = (mouseX - this.panX) / this.scale
      const mouseCanvasY = (mouseY - this.panY) / this.scale

      // 计算新的平移量，使鼠标位置保持不变
      const newPanX = mouseX - mouseCanvasX * newScale
      const newPanY = mouseY - mouseCanvasY * newScale

      this.updateCanvasTransform({
        scale: newScale,
        panX: newPanX,
        panY: newPanY
      })
    },

    // 处理鼠标按下
    handleMouseDown(event) {
      const target = event.target

      // 如果点击的是节点或节点的子元素，不处理画布拖拽
      if (target.closest('.node')) {
        console.log('🖱️ Canvas handleMouseDown - 忽略节点点击')
        return
      }

      console.log('🖱️ Canvas handleMouseDown', {
        target: event.target,
        className: target?.className
      })
      // 记录初始鼠标位置,并标记为拖拽状态
      this.isDragging = true
      this.lastMouseX = event.clientX
      this.lastMouseY = event.clientY
      this.selectNode({ nodeId: null }) // 取消选中
    },

    // 处理鼠标移动
    handleMouseMove(event) {
      if (this.isDragging) {
        const deltaX = event.clientX - this.lastMouseX// 计算鼠标移动的距离
        const deltaY = event.clientY - this.lastMouseY
        // 更新画布的平移量
        this.updateCanvasTransform({
          scale: this.scale,
          panX: this.panX + deltaX,
          panY: this.panY + deltaY
        })
        // 记录当前鼠标位置
        this.lastMouseX = event.clientX
        this.lastMouseY = event.clientY
      }
    },

    // 处理鼠标释放
    handleMouseUp() {
      this.isDragging = false
    },

    // 处理节点选择
    handleNodeSelect(nodeId, event) {
      const ctrlKey = event && event.ctrlKey
      this.selectNode({ nodeId, ctrlKey })
    },

    // 从工具栏添加节点
    handleAddNode() {
      this.showNodeLibrary = !this.showNodeLibrary
    },

    // 从节点库添加节点
    handleAddNodeFromLibrary(template) {
      const newNode = {
        id: `node_${Date.now()}`,
        title: template.name || '新节点',
        x: 200 + Math.random() * 300,
        y: 200 + Math.random() * 300,
        type: template.type || 'table',
        style: {
          width: 200,
          height: 120,
          backgroundColor: '#F5F5F5',
          borderColor: '#CCCCCC'
        },
        fields: template.fields || [
          { name: 'id', type: 'INT', isPrimaryKey: true, isRequired: true },
          { name: 'name', type: 'VARCHAR(100)', isPrimaryKey: false, isRequired: true }
        ]
      }
      this.addNodeToStore(newNode)
      this.$message.success(`已添加节点：${template.name || '新节点'}`)
    },

    // 处理保存
    handleSave() {
      this.$message.success('布局已保存到本地存储')
    },

    // 处理重置
    handleReset() {
      this.$confirm('确定要重置画布吗？这将重置画布位置和缩放。', '确认重置', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateCanvasTransform({
          scale: 1,
          panX: 0,
          panY: 0
        })
        this.$message.success('画布已重置')
      }).catch(() => {
        this.$message.info('已取消重置')
      })
    }
  }
}
</script>

<style scoped>
.canvas-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.node-library {
  width: 250px;
  background-color: white;
  border-right: 1px solid #e0e0e0;
  overflow-y: auto;
}

.canvas-area {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.nodes-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.nodes-container>* {
  pointer-events: auto;
}

.canvas-area:active {
  cursor: grabbing;
}

.canvas-svg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  overflow: visible;
}
</style>